import React from "react";
import style from "./Register.module.scss";
import {Button, Form, Input, message, Space, Typography} from "antd";
import {UserAddOutlined} from "@ant-design/icons";
import {Link, useNavigate} from "react-router-dom";
import {useRequest} from "ahooks";
import {registerService} from "../service/user";
import {LOGIN_PATHNAME} from "../constants";

const {Title} = Typography;
const Register: React.FC = () => {
  const nav = useNavigate()
  const {run} = useRequest(async (username: string, password: string, nickname: string) => {
    await registerService(username, password, nickname)
  }, {
    manual: true,
    onSuccess(result) {
      message.success("注册成功")
      nav(LOGIN_PATHNAME)
    }
  })

  function onFinish(value: any) {
    const {username, nickname, password} = value
    run(username, password, nickname)
    console.log(value);
  }

  return (
    <div className={style.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined/>
          </Title>
          <Title level={2}>注册新用户</Title>
        </Space>
      </div>
      <div>
        <Form
          name="basic"
          labelCol={{span: 8}}
          wrapperCol={{span: 16}}
          initialValues={{remember: true}}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item label="用户名" name="username"
                     rules={[{required: true, message: '请输入用户名'}, {
                       type: "string", min: 5, max: 20, message: '用户名长度在5-20'
                     }]}>
            <Input/>
          </Form.Item>

          <Form.Item label="密码" name="password"
                     rules={[{required: true, message: '请输入密码'}]}>
            <Input.Password/>
          </Form.Item>

          <Form.Item label="确认密码" name="confirm"
                     dependencies={['password']}
                     rules={[{required: true, message: '请输入用户名'}, ({getFieldValue}) => ({
                       validator(_, value) {
                         if (!value || value === getFieldValue('password')) {
                           return Promise.resolve()
                         } else {
                           return Promise.reject(new Error('两次密码不一致'))
                         }
                       }
                     })]}>
            <Input.Password/>
          </Form.Item>

          <Form.Item label="昵称" name="nickname">
            <Input.Password/>
          </Form.Item>

          <Form.Item wrapperCol={{offset: 8, span: 16}}>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
            <Link to={"/login"}>已有账号，登录</Link>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Register;
